package com.hoo.controller.account;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Encodes;

import com.hoo.common.constant.Result;
import com.hoo.entity.account.Users;
import com.hoo.entity.flow.FlowUserAction;
import com.hoo.form.account.UsersForm;
import com.hoo.service.account.AccountService;
import com.hoo.service.flow.FlowUserActionService;
import com.hoo.util.AuthUtils;
import com.hoo.util.IpUtils;
import com.hoo.util.PaginationSupport;

@Controller
@RequestMapping("/account")
public class AccountController extends BaseController {

	@Autowired
	private AccountService accountService;

	@Autowired
	private FlowUserActionService flowUserActionService;

	@ExceptionHandler(Exception.class)
	public String exception(Exception e, HttpServletRequest request) {
		request.setAttribute("exception", e);
		return "/error";
	}

	/**
	 * 检查该用户名是否已经存在
	 * 
	 * @param loginName
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/check_user_name", method = RequestMethod.POST)
	@ResponseBody
	public String checkUsername(@RequestParam String loginName,
			HttpServletRequest request) {
		return this.accountService.getUserByLoginName(loginName) != null ? "false"
				: "true";
	}

	/**
	 * 用户的修改和添加
	 * 
	 * @param operationType
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/update_user/{operationType}", method = RequestMethod.GET)
	public String updateUser(@PathVariable String operationType, Model model) {
		model.addAttribute("operationType", operationType);
		if ("add".equals(operationType)) {

		}
		return "account/updateUser";
	}

	/**
	 * 用户的修改和添加
	 * 
	 * @param form
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/update_user", method = RequestMethod.POST)
	@ResponseBody
	public String doUpdateUser(UsersForm form, HttpServletRequest request) {
		try {
			if (form.getId() == null) { // 此时为添加
				form.setAddBy(this.getCurrentUserId());
				return accountService.saveUser(form) != 1 ? "fail" : "success";
			}
			return this.accountService.updateUser(form) == 1 ? "success"
					: "fail";
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return "fail";
	}

	@RequestMapping(value = "/delete_user", method = RequestMethod.POST)
	@ResponseBody
	public String doDeleteUser(@RequestParam int userid,
			HttpServletRequest request) {
		UsersForm form = new UsersForm();
		form.setId(userid);
		form.setUserFlag(2);
		return this.accountService.updateUser(form) != 1 ? "fail" : "success";
	}

	@RequestMapping(value = "/user_list", method = RequestMethod.GET)
	public String userList() {
		return "account/managerUsers";
	}

	/**
	 * 获取用户列表
	 * 
	 * @param form
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/search_user_list", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> searchUserList(UsersForm form,
			HttpServletRequest request) {
		PaginationSupport<Users> ps = this.accountService.searchUserList(form);
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}

	/**
	 * 修改登录密码
	 * 
	 * @param update_pwd
	 * @return
	 */
	@RequestMapping(value = "/update_pwd", method = RequestMethod.GET)
	public String updatePwd(@ModelAttribute("form") UsersForm form,
			BindingResult result) {
		return "account/updatePwd";
	}

	/*
	 * @RequestMapping(value = "/update_pwd", method = RequestMethod.POST)
	 * public String doUpdatePwd(@Valid @ModelAttribute("form") UsersForm form,
	 * BindingResult result,HttpServletRequest request, RedirectAttributes
	 * redirectAttributes) { redirectAttributes.addFlashAttribute("message",
	 * "修改失败！"); try { Users users = this.getUserContext().getUser(); if
	 * (!users.getLoginPassword().equals(
	 * AuthUtils.encryptPlainPassword(form.getLoginPassword(),
	 * Encodes.decodeHex(users.getSalt())))) { Result result1 = new Result();
	 * Errors errors = new BeanPropertyBindingResult(new UsersForm(), "form");
	 * errors.rejectValue("loginPassword", "", "原密码输入错误");
	 * result1.setErrors(errors); result.addAllErrors(result1.getErrors());
	 * //redirectAttributes.addFlashAttribute("message", "原密码输入错误"); //return
	 * "account/updatePwd"; return updatePwd(form,result); }
	 * users.setLoginPassword(AuthUtils.encryptPlainPassword(
	 * form.getNewLoginPassword(), Encodes.decodeHex(users.getSalt())));
	 * 
	 * if (this.accountService.updateUserLoginInfo(users) == 1) { // 记录日志
	 * FlowUserAction flowUserAction = new FlowUserAction();
	 * flowUserAction.setType(2);// 1:登录，2：修改，3：增加，4：删除
	 * flowUserAction.setUserId(getCurrentUserId());
	 * flowUserAction.setRemark("修改密码");
	 * flowUserAction.setIp(IpUtils.getIpAddr(request));
	 * flowUserAction.setAddTime(new Date());
	 * flowUserActionService.insert_flow_user_action(flowUserAction);
	 * redirectAttributes.addFlashAttribute("message", "修改成功！"); } } catch
	 * (Exception e) { e.printStackTrace(); } return
	 * "redirect:/account/update_pwd"; }
	 */

	/**
	 * 修改登录密码
	 * 
	 * @param form
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/update_pwd", method = RequestMethod.POST)
	public String doUpdatePwd(UsersForm form, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		redirectAttributes.addFlashAttribute("message", "修改失败！");
		try {
			Users users = this.getUserContext().getUser();
			if (!users.getLoginPassword().equals(
					AuthUtils.encryptPlainPassword(form.getLoginPassword(),
							Encodes.decodeHex(users.getSalt())))) {
				redirectAttributes.addFlashAttribute("message", "原密码输入错误");
				return "account/updatePwd";
			}
			users.setLoginPassword(AuthUtils.encryptPlainPassword(
					form.getNewLoginPassword(),
					Encodes.decodeHex(users.getSalt())));

			if (this.accountService.updateUserLoginInfo(users) == 1) {
				// 记录日志
				FlowUserAction flowUserAction = new FlowUserAction();
				flowUserAction.setType(2);// 1:登录，2：修改，3：增加，4：删除
				flowUserAction.setUserId(getCurrentUserId());
				flowUserAction.setRemark("修改密码");
				flowUserAction.setIp(IpUtils.getIpAddr(request));
				flowUserAction.setAddTime(new Date());
				flowUserActionService.insert_flow_user_action(flowUserAction);
				redirectAttributes.addFlashAttribute("message", "修改成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/account/update_pwd";
	}

	/**
	 * 修改密码，ajax提交形式
	 */

	/*
	 * @RequestMapping(value = "/update_pwd", method = RequestMethod.POST)
	 * 
	 * @ResponseBody public String doUpdatePwd(UsersForm form,
	 * HttpServletRequest request) { try { Users users =
	 * this.getUserContext().getUser(); if (!users.getLoginPassword().equals(
	 * AuthUtils.encryptPlainPassword(form.getLoginPassword(),
	 * Encodes.decodeHex(users.getSalt())))) { return "oldError"; }
	 * users.setLoginPassword(AuthUtils.encryptPlainPassword(
	 * form.getNewLoginPassword(), Encodes.decodeHex(users.getSalt())));
	 * 
	 * if (this.accountService.updateUserLoginInfo(users) == 1) { // 记录日志
	 * FlowUserAction flowUserAction = new FlowUserAction();
	 * flowUserAction.setType(2);// 1:登录，2：修改，3：增加，4：删除
	 * flowUserAction.setUserId(getCurrentUserId());
	 * flowUserAction.setRemark("修改密码");
	 * flowUserAction.setIp(IpUtils.getIpAddr(request));
	 * flowUserAction.setAddTime(new Date());
	 * flowUserActionService.insert_flow_user_action(flowUserAction); return
	 * "success"; } } catch (Exception e) { e.printStackTrace(); } return
	 * "fail"; }
	 */
	/**
	 * 查询用户安全日志
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user_logs", method = RequestMethod.GET)
	public String viewUserActionLogs(Model model) {
		model.addAttribute("logs", this.flowUserActionService
				.getUserActionList(getCurrentUserId()));
		return "account/safeLog";
	}

	/**
	 * 查询用户安全日志
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user_logs", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> showUserActionLogs() {
		PaginationSupport<FlowUserAction> ps = this.flowUserActionService
				.search(getCurrentUserId());
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}

	/**
	 * 用户详细信息
	 * 
	 * @param form
	 * @param result
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/user_info", method = RequestMethod.GET)
	public String userInfo(@ModelAttribute("form") Users form,
			BindingResult result, Model model) {
		Users user = this.accountService
				.getAccountById(this.getCurrentUserId());
		if (result.hasErrors()) {
			model.addAttribute("updateResult", "fail");
		}
		model.addAttribute("currentUser", user);
		return "account/userInfo";
	}

	/**
	 * 检查原登录密码是否正确
	 * 
	 * @param loginPassword
	 * @return
	 */
	@RequestMapping(value = "/check_loginPassword", method = RequestMethod.POST)
	@ResponseBody
	public String checkLoginPassword(@RequestParam String loginPassword) {
		Users users = this.getUserContext().getUser();
		if (!users.getLoginPassword().equals(
				AuthUtils.encryptPlainPassword(loginPassword,
						Encodes.decodeHex(users.getSalt())))) {
			return "false";
		}
		return "true";
	}

}